class jiacha_obj:
    """多腿价差合约实时计算器"""
    def __init__(self,legs=[]):
        self.legs = []  # 存储各腿配置 [品种,比例]
        self.last_prices = {}  # 最新价格缓存
        for leg in legs:
            self.add_leg(leg[0],leg[1])

    def add_leg(self, symbol: str, ratio: float):
        """添加交易腿配置
        :param symbol: 品种代码
        :param ratio: 该腿权重比例(可正可负)
        """
        self.legs.append((symbol, ratio))
        self.last_prices[symbol] = 0.0
    def on_tick(self, symbol: str, price: float):
        """处理tick更新"""
        self.update_tick(symbol, price)
        spread = self.calculate_spread()
        return spread
    def update_tick(self, symbol: str, price: float):
        """更新品种最新价格
        :param symbol: 品种代码
        :param price: 最新成交价
        """
        if symbol in self.last_prices:
            self.last_prices[symbol] = price

    def calculate_spread(self):
        """计算实时价差(加权求和)"""
        spread = 0.0
        for symbol, ratio in self.legs:
            spread += self.last_prices.get(symbol, 0) * ratio
        return round(spread, 4)


# 使用示例
if __name__ == "__main__":
    # 创建三腿价差合约(如跨品种套利)
    contract = jiacha_obj()
    contract.add_leg("CU2407", 1)  # 沪铜主力合约
    contract.add_leg("AL2407", -2)  # 沪铝主力合约
    contract.add_leg("ZN2407", 1)  # 沪锌主力合约

    # 模拟tick更新
    contract.update_tick("CU2407", 68230)
    contract.update_tick("AL2407", 19250)
    contract.update_tick("ZN2407", 21580)

    print(f"实时价差: {contract.calculate_spread()}")
